<?php
namespace app\index\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use app\common\model\News;
class Epay extends Base
{
  
     public function yongjin($jine,$out_trade_no)
    {
 
    $orders= Db::name('order')->where('out_trade_no',$out_trade_no)->find();
    $dailidata=Db::name('daili')->where('id',$orders['dailiuid'])->find(); 
    $shuilvdata=Db::name('dailiconfig')->where('dengji',$dailidata['status'])->find();
    $shuilv= $shuilvdata['yongjinbaifenbi'] / 100;
  
      $dailiyongjin=$orders['price']* $shuilv;
      $myyongjin=$orders['price']*(1-$shuilv);
      Db::name('daili')->where('id',$dailidata['id'])->inc('yue',$dailiyongjin)->update();
      Db::name('tongji')->where('id',1)->inc('zongshouru',$myyongjin)->update();
  
}
    public function index()
    {
         error_reporting(E_ERROR | E_WARNING | E_PARSE);
        $iddata= input('get.');
      $dailiData = Db::name('daili')->where('dwz',$iddata['dwz'])->find();//一维数组
      if($dailiData['zidingyi']==1){
       $uid= 0;   
      }else{
        $uid= $dailiData['id'];    
      }
       
       $id = $iddata['id'];
       $payconfig= Db::name('pay')->where(['state'=>'1'])->limit(1)->orderRaw("rand() , id DESC")->select();
    $config= Db::name('danqun')->where("uid",$uid)->find();
    $namedata=json_decode($config['name'],true); 
       
        //商品名称
 
		//站点名称
     if(strpos($namedata['price'],',') !== false){ 
         $var=explode(",",$namedata['price']);
          if ($var[0] > $var[1]) {
        $numMax = $var[0];
        $numMin = $var[1];
         } else {
        $numMax = $var[1];
        $numMin = $var[0];
         }
         $rand = $numMin + mt_rand() / mt_getrandmax() * ($numMax - $numMin);
         $orderdata['price'] = number_format($rand,1);
     }else{
         $orderdata['price'] = $namedata['price'];
     } 
        //必填
    $orderdata['uid'] = $id;
    $orderdata['status'] = "1";
    $orderdata['time'] = time();
  
   
    $orderdata['out_trade_no'] = date('YmdHis') . rand(10000000,99999999);
    $orderdata['sitename'] = $namedata['jishuzhichi'];
    $orderdata['payqudao'] = $payconfig[0]['qudao'];
    $orderdata['paybiaoshi'] = $payconfig[0]['biaoshi'];
    $orderdata['name'] = $namedata['sname'];
    $orderdata['dailiuid'] = $dailiData['id'];
    $orderdata['type'] = "1";
    $orderdata['payid'] = $payconfig[0]['id'];

    $res= Db::name('order')->insertGetId($orderdata);     
$epay_config['apiurl'] = $payconfig['url'];

//商户ID
$epay_config['pid'] = $payconfig['app_Id'];

//商户密钥
$epay_config['key'] = $payconfig['app_key'];

       if($payconfig[0]['biaoshi']=='epay'){
       Header("Location:/index/epay/epay?id=".$res); 
       }elseif ($payconfig[0]['biaoshi']=='codepay') {
       Header("Location:/index/epay/codepay?id=".$res);  
       }else{
           echo("支付通道配置错误，请修改后重试");
       }
        
    }
    public function epay()
    {
          error_reporting(E_ERROR | E_WARNING | E_PARSE);
// require_once (root_path().'/extend/epay/lib/epay.config.php');
require_once (root_path().'/extend/epay/lib/EpayCore.class.php');

  $id = input('id');
  $config= Db::name('order')->where("id",$id)->find();
  $pay= Db::name('pay')->where("id",$config['payid'])->find();
  $payconfig= Db::name('urls')->where(['status'=>'1'])->where(['type'=>'2'])->limit(1)->orderRaw("rand() , id DESC")->select();

  //支付接口地址
$epay_config['apiurl'] = $pay['url'];

//商户ID
$epay_config['pid'] = $pay['app_Id'];

//商户密钥
$epay_config['key'] = $pay['app_key'];

        $notify_url =  "http://".$payconfig[0]['url']."/index/epay/notify";
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        $return_url =  "http://".$payconfig[0]['url']."/index/epay/return";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        //商户订单号
        
     
        //商户网站订单系统中唯一订单号，必填

		//支付方式

        //订单描述


/************************************************************/

//构造要请求的参数数组，无需改动
$parameter = array(
	"pid" => $epay_config['pid'],
	"type" => $config['payqudao'],
	"notify_url" => $notify_url,
	"return_url" => $return_url,
	"out_trade_no" => $config['out_trade_no'],
	"name" => $config['name'],
	"money"	=> $config['price'],
);

//建立请求
$epay = new \EpayCore($epay_config);
$html_text = $epay->pagePay($parameter);
echo $html_text;
}
public function codepay()
    {
          error_reporting(E_ERROR | E_WARNING | E_PARSE);
// require_once (root_path().'/extend/epay/lib/epay.config.php');
require_once (root_path().'/extend/epay/lib/EpayCore.class.php');

  $id = input('id');
  $config= Db::name('order')->where("id",$id)->find();
  $pay= Db::name('pay')->where("id",$config['payid'])->find();
  $payconfig= Db::name('urls')->where(['status'=>'1'])->where(['type'=>'2'])->limit(1)->orderRaw("rand() , id DESC")->select();

  //支付接口地址
$epay_config['apiurl'] = $pay['url'];

//商户ID
$epay_config['pid'] = $pay['app_Id'];

//商户密钥
$epay_config['key'] = $pay['app_key'];

        $notify_url =  "http://".$payconfig[0]['url']."/index/epay/notify";
        //需http://格式的完整路径，不能加?id=123这类自定义参数

        //页面跳转同步通知页面路径
        $return_url =  "http://".$payconfig[0]['url']."/index/epay/return";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

        //商户订单号
        
     
        //商户网站订单系统中唯一订单号，必填

		//支付方式

        //订单描述


/************************************************************/

//构造要请求的参数数组，无需改动
$parameter = array(
	"pid" => $epay_config['pid'],
	"type" => $config['payqudao'],
	"notify_url" => $notify_url,
	"return_url" => $return_url,
	"out_trade_no" => $config['out_trade_no'],
	"name" => $config['name'],
	"money"	=> $config['price'],
);

//建立请求
$epay = new \EpayCore($epay_config);
$html_text = $epay->pagePay($parameter);
echo $html_text;
}
 public function notify()//异步通知
    {

/* *
 * 功能：彩虹易支付异步通知页面
 * 说明：
 * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
 */

require_once (root_path().'/extend/epay/lib/epay.config.php');
require_once (root_path().'/extend/epay/lib/EpayCore.class.php');

//计算得出通知验证结果
$epay = new \EpayCore($epay_config);
$verify_result = $epay->verifyNotify();
 $data = input('get.');


	//商户订单号
	$out_trade_no = $data['out_trade_no'];

	//彩虹易支付交易号
	$trade_no = $data['trade_no'];

	//交易状态
	$trade_status = $data['trade_status'];

	//支付方式
	$type = $data['type'];

	//支付金额
	$money = $data['money'];
   
   
  
    
    
	if ($data['trade_status'] == 'TRADE_SUCCESS') {
	     $order=Db::name('order')->where('out_trade_no',$out_trade_no)->update(['status'=>2,'paytime'=>time()]);
	    
	   $tongzhidata=Db::name('tongzhi')->where('id',1)->find();   
        if($tongzhidata['fufei']==2){
         $orderdata=Db::name('order')->where('out_trade_no',$out_trade_no)->find();
	     $dailidata=Db::name('daili')->where('id',$orderdata['dailiuid'])->find();

        $post_data='
      {
    "msgtype": "markdown",
    "markdown": {
        "content": "用户付款通知<font color=\"warning\">所属代理：'. $dailidata['beizhu']. '</font>。\n
         >类型:<font color=\"comment\">用户付款通知</font>
         >金额:<font color=\"comment\">'.$orderdata['price'].'元</font>
         >订单编号:<font color=\"comment\">'.$orderdata['out_trade_no'].'</font>"
    }
   }';
 
     $result = $this->tongzhi($post_data);  
   }
	    
	     $result = $this->yongjin($money,$out_trade_no);
		//判断该笔订单是否在商户网站中已经做过处理
		//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
		//如果有做过处理，不执行商户的业务程序
	}

	//验证成功返回
	echo "success";


       
 
    }
 public function return()
    {
    //计算得出通知验证结果
 require_once (root_path().'/extend/epay/lib/epay.config.php');
require_once (root_path().'/extend/epay/lib/EpayCore.class.php');   
$epay = new \EpayCore($epay_config);
$verify_result = $epay->verifyReturn();
 $data = input('get.');


	//商户订单号
	$out_trade_no = $data['out_trade_no'];

	//支付宝交易号
	$trade_no = $data['trade_no'];

	//交易状态
	$trade_status = $data['trade_status'];

	//支付方式
	$type = $data['type'];


	if($data['trade_status'] == 'TRADE_SUCCESS') {
	$paiddata= Db::name('order')->where('out_trade_no',$out_trade_no)->find();   
	$dailidata= Db::name('daili')->where('id',$paiddata['dailiuid'])->find();  
    return alert('支付成功，即将进入支付成功页面','/index/qun/paid?dwz='.$dailidata['dwz'],6,3);
      
	}



   
  
}
}
